/**
 * Copyright ©2012-2018 HopeHaiyang Corporation, All Rights Reserved
 * http://www.wuhanhope.com
 */
package hujia.profile.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

/**
 * class info
 *
 * @author hujia
 *         Create at 2018/7/30 16:32
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    AuthenticationManagerBuilder authenticationManager;
    @Autowired
    UserDetailsService userDetailsService;


    @Override
    public void configure(ClientDetailsServiceConfigurer client) throws Exception {
        client.inMemory()
                //用户名
                .withClient("web")
                //授权方式
                .authorizedGrantTypes("password", "authorization_code", "refresh_token")
                //作用域
                .scopes("read", "write")
                //密码
                .secret("{noop}hope123")
                //权限(与角色绑定)
                .authorities("ROLE_site", "ROLE_user")
                //获得时效
                .accessTokenValiditySeconds(240)
                //刷新时效
                .refreshTokenValiditySeconds(480);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.userDetailsService(userDetailsService).
                authenticationManager(new AuthenticationManager() {
                    @Override
                    public Authentication authenticate(Authentication authentication)
                            throws AuthenticationException {
                        return authenticationManager.getOrBuild().authenticate(authentication);
                    }
                });
    }


}
